import React, { useState } from 'react';

const CommentInput = (props) => {
  const [user, setUser] = useState('');
  const [rating, setRating] = useState('');
  const [comments, setComments] = useState('');

  function handleUserChange(e) {
    setUser(e.target.value);
  }
  function handleRatingChange(e) {
    setRating(Number(e.target.value));
  }
  function handleCommentsChange(e) {
    setComments(e.target.value);
  }

  function submit() {
    const newComments = props.comments.concat({
      id: props.comments[props.comments.length - 1].id + 1,
      user,
      rating,
      comments,
    });
    props.setComments(newComments);

    // 初始化，清空输入框
    setUser('');
    setRating('');
    setComments('');
  }

  return (
    <div>
      <div>
        用户：
        <input type="text" value={user} onChange={handleUserChange} />
      </div>
      <div>
        评分：
        <input type="text" value={rating} onChange={handleRatingChange} />
      </div>
      <div>
        评论：
        <textarea rows="4" cols="50" value={comments} onChange={handleCommentsChange} />
      </div>
      <br />
      <div>
        <input type="button" value="提交" onClick={submit} />
      </div>
    </div>
  );
};

export default CommentInput;
